
package com.yuan.application;

import com.yuan.unit.BLog;

import java.util.ArrayList;

/**
 * 主要用于退出程序时调用
 * 
 * @author YUAN
 */
public class ApplicationCleaner {
    private volatile static ApplicationCleaner sInstance;
    private ArrayList<OnMyDestroyListener> mListeners;

    private ApplicationCleaner() {
        mListeners = new ArrayList<OnMyDestroyListener>();
    }

    public static ApplicationCleaner getInstance() {
        if (sInstance == null) {
            synchronized (ApplicationCleaner.class) {
                if (sInstance == null) {
                    sInstance = new ApplicationCleaner();
                }
            }
        }
        return sInstance;
    }

    public final void registerApplicationDestroyListener(OnMyDestroyListener lis) {
        if (lis != null && !mListeners.contains(lis)) {
            BLog.d(lis.getClass().getName(),
                    "registerApplicationDestroyListener for " + lis.getClass().getName());
            mListeners.add(lis);
        }
    }

    public final void unRegisterApplicationDestroyListener(OnMyDestroyListener lis) {
        if (lis != null && mListeners.contains(lis)) {
            BLog.d(lis.getClass().getName(),
                    "unRegisterApplicationDestroyListener for " + lis.getClass().getName());
            mListeners.remove(lis);
        }
    }

    public void onApplicationDestroy() {
        for (int i = mListeners.size() - 1; i > -1; i--) {
            OnMyDestroyListener lis = mListeners.get(i);
            try {
                BLog.d(lis.getClass().getName(),
                        "Calling destroy for " + lis.getClass().getName());
                lis.onMyDestroy();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        System.exit(0);
        android.os.Process.killProcess(android.os.Process.myPid());
        mListeners.clear();
        sInstance = null;
    }
}
